import fs = require("fs")
import path = require("path")
import { SocketConnection } from "./SocketConnection";
import { Logger } from "../../utils/Logger";

export class SocketConnectionManager {

    public static instance: SocketConnectionManager = new SocketConnectionManager();

    public socketConnList: Array<SocketConnection> = [];

    public init() {
        this.socketConnList = [];
    }

    /* 
   增加客户端socket连接
    */
    public addSocketConnection(conn: SocketConnection) {
        this.socketConnList.push(conn);
    }

    public getSocketConnection(id: number) {
        for (let i = 0; i < this.socketConnList.length; i++) {
            let conn: SocketConnection = this.socketConnList[i];
            if (conn.id == id) {
                return conn;
            }
        }
    }

    public getSocketConnectionByUser(account: string, socketConn: SocketConnection) {
        let result: SocketConnection;
        for (let i = 0; i < this.socketConnList.length; i++) {
            let conn: SocketConnection = this.socketConnList[i];
            if (conn.id != socketConn.id) {
                if (!conn.isClosing && conn.user && conn.user.userName == account) {
                    result = conn;
                    break;
                }
            }
        }
        return result
    }

    /* 
    删除客户端socket连接
     */
    public removeSocketConnection(removeOne: SocketConnection) {
        if (!removeOne) {
            return;
        }
        for (let i = 0; i < this.socketConnList.length; i++) {
            let conn: SocketConnection = this.socketConnList[i];
            if (conn.id == removeOne.id) {
                this.socketConnList.splice(i, 1);
                return;
            }
        }
    }


    // public sendMsgToUser(user:UserModel, totalPack){
    //     let conn: SocketConnection = SocketConnectionManager.instance.getSocketConnectionByUser(user.userId, user.isPlayer)
    //     if (conn) {
    //         conn.sendMsgToClient(totalPack);
    //     }
    // }

    // public deleteConnectionUser(user:UserModel){
    //     let conn: SocketConnection = SocketConnectionManager.instance.getSocketConnectionByUser(user.userId, user.isPlayer)
    //     if (conn) {
    //         conn.user = null;
    //     }
    // }
}